package com.ley.springboot.commons.utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.lang.reflect.Type;
import java.util.List;

/**
 * google json utility class
 *
 * @author 2036185346@qq.com
 * @see Gson
 **/
public class GsonUtils {

    /**
     * default date format
     **/
    public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";


    /**
     * get google json
     **/
    public static Gson getGson() {
        return (new GsonBuilder()).serializeNulls().setDateFormat(GsonUtils.DEFAULT_DATE_FORMAT).create();
    }


    //object to json

    /**
     * object to json
     **/
    public static String obj2Json(Object obj) {
        return getGson().toJson(obj);
    }

    /**
     * json to type
     *
     * @see Gson#toJson(Object, Type)
     **/
    public static String obj2Json(Object obj, Type typeOfObj) {
        return getGson().toJson(obj, typeOfObj);
    }

    /**
     * generic t to json
     **/
    public static <T> String t2Json(T t) {
        return getGson().toJson(t);
    }


    //json to object

    /**
     * json to generic t
     **/
    public static <T> T json2T(String jsonStr, Class<T> classOfT) {
        return getGson().fromJson(jsonStr, classOfT);
    }

    /**
     * json to collection
     **/
    public static <T> List<T> json2List(String jsonStr, Type typeOfT) {
        return (List<T>) getGson().fromJson(jsonStr, typeOfT);
    }

    /**
     * json to type
     *
     * @see Gson#fromJson(String, Type)
     * @see com.google.gson.reflect.TypeToken
     **/
    public static <T> T json2Obj(String jsonStr, Type typeOfT) {
        return getGson().fromJson(jsonStr, typeOfT);
    }
}
